//
//  KKDES.m
//  TradingPlatform
//
//  Created by 程强 on 15/11/25.
//  Copyright © 2015年 程强. All rights reserved.
//

#import "KKDES.h"
#import "GTMBase64.h"
#import <CommonCrypto/CommonCryptor.h>

@implementation KKDES
+(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key
{
     NSString *ciphertext = nil;
     const char *textBytes = [plainText UTF8String];
     NSUInteger dataLength = [plainText length];
     unsigned char buffer[1024];
     memset(buffer, 0, sizeof(char));
     size_t numBytesEncrypted = 0;
    
     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                                                                        kCCOptionPKCS7Padding,
                                                                                        [key UTF8String], kCCKeySizeDES,
                                                                                        [key UTF8String],
                                                                                        textBytes, dataLength,
                                                                                        buffer, 1024,
                                                                                        &numBytesEncrypted);

     if (cryptStatus == kCCSuccess) {
             NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
             ciphertext = [GTMBase64 stringByEncodingData:data];
         }
     return ciphertext;
}
//解密
+ (NSString *) decryptUseDES:(NSString*)cipherText key:(NSString*)key
{
    NSData* cipherData = [GTMBase64 decodeString:cipherText];
    unsigned char buffer[1024];
    memset(buffer, 0, sizeof(char));
    size_t numBytesDecrypted = 0;
    
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding,
                                          [key UTF8String],
                                          kCCKeySizeDES,
                                          [key UTF8String],
                                          [cipherData bytes],
                                          [cipherData length],
                                          buffer,
                                          1024,
                                          &numBytesDecrypted);
    NSString* plainText = nil;
    if (cryptStatus == kCCSuccess) {
        NSData* data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
        plainText = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    }
    return plainText;
}
@end
